import type { UserInfo } from '@/apis/model/auth'
import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useAppStore = defineStore(
  storesKey.app,
  () => {
    const token = ref('')
    const router = useRouter()
    const userInfo = ref<UserInfo>()
    const nodeStatistic = ref<any>({
      region_id: '',
      node_ids: [],
      timeDate: '',
      isHour: true,
      selectRadio: ''
    })
    const siteStatistic = ref<any>({
      region_id: '',
      site_ids: [],
      timeDate: '',
      selectRadio: ''
    })
    const updateNodeStatistic = (statistic: any) => {
      nodeStatistic.value = statistic
    }
    const updateSiteStatistic = (statistic: any) => {
      siteStatistic.value = statistic
    }
    const initNodeStatistic = () => {
      nodeStatistic.value = {
        region_id: '',
        node_ids: [],
        timeDate: '',
        isHour: true,
        selectRadio: ''
      }
    }

    const initSiteStatistic = () => {
      siteStatistic.value = {
        region_id: '',
        site_ids: [],
        timeDate: '',
        selectRadio: ''
      }
    }
    // 级联视频提示dialog是否展示过
    const nodeCascadeVideoTipsShowed = ref(false)
    const setNodeCascadeVideoTipsShowed = (show: boolean) => {
      nodeCascadeVideoTipsShowed.value = show
    }
    const saveToken = (value: string) => {
      token.value = value
    }
    const updateUserInfo = (value: UserInfo) => {
      userInfo.value = value
    }
    const clearLoginInfoAction = () => {
      token.value = ''
      userInfo.value = undefined
      localStorage.removeItem(storesKey.app)
      router.replace('/sign-in')
    }

    const logout = () => {
      CloudModal.warn(
        {
          content: '确定要退出系统吗？'
        },
        async () => {
          clearLoginInfoAction()
        }
      )
    }
    return {
      token,
      userInfo,
      saveToken,
      logout,
      updateUserInfo,
      clearLoginInfoAction,
      nodeCascadeVideoTipsShowed,
      setNodeCascadeVideoTipsShowed,
      nodeStatistic,
      updateNodeStatistic,
      siteStatistic,
      updateSiteStatistic,
      initNodeStatistic,
      initSiteStatistic
    }
  },
  {
    persist: true
  }
)
